setTimeout(async function () {

    if (webError()) {
        let errorTime = await session.get("error_time", null);
        if (!!!errorTime) {
            await session.set("error_time", new Date().getTime());
        }
        return;
    }

    let stopService = await session.get("stopService", false)
    if (stopService) {
        await session.set("msg", "当前时间段内,插件停止服务")
        return;
    }

    await checkLogin();

    await login();

    await statusDiv();

    await emailSkip();

}, 2000);

//current_step = checkLogin
async function checkLogin() {
    let currentStep = await session.get("current_step", null);
    let account = await session.get("account", null);
    if (currentStep == "checkLogin") {
        //如果不是 右上角 有登陆信息的页面  就先跳转到右上角有 登陆信息的页面
        if (window.location.href != 'https://ecomm.one-line.com/one-ecom'
            && window.location.href != 'https://ecomm.one-line.com/one-ecom/'
            && window.location.href.indexOf('auth-ui/v2/login') == -1) {
            window.location.href = 'https://ecomm.one-line.com/one-ecom'
            return
        }
        //根据右上角的信息 判断是否登陆
        let loginSucc = $('#avatar-icon').filter(function (index) {
            return this.innerHTML.indexOf("AfterLoginAvatarPopover") != -1;
        });

        let succ = false;
        if (!!loginSucc && loginSucc.length > 0) {
            await session.set("loginStatus", true);
            succ = true;
        } else {
            await session.remove("loginStatus");
        }

        if (!!succ) {
            var message = {"from": "extenstion", "action": "localStorage_get"};
            window.postMessage(message, "*");
            sendMsg({action: 'getCookie', domain: '.one-line.com'})

            await localTimeFunction(async function () {
                await session.set("current_step", "getToken");
                await session.set("current_step_time", new Date().getTime());

                await session.set("msg", "登陆成功，获取账号cookie等信息，然后准备上传")
                console.log("checkLogin: 获取cookie")
            }, 2000)
        } else {
            let hasDoneLogin = await session.get("hasDoneLogin", false);
            let hasDoneLogin_time = await session.get("hasDoneLogin_time", 0);
            if (hasDoneLogin && new Date().getTime() - hasDoneLogin_time < 60000) {
                console.log("checkLogin: 登陆失败")
                await session.set("msg", "登陆失败")

                if (!!account) {
                    core.updateAccount(Object.assign(account, {
                        otherCache: null,
                        apiToken: null,
                        remark: "plugin_remark_error"
                    }))
                }

                await getAccountAndRefresh();
                return;
            } else {
                if (!!account) {
                    await session.set("msg", "重新登陆: " + account['username'])
                    console.log("checkLogin: 重新登陆")
                    await session.set("current_step", "login");
                    await session.set("current_step_time", new Date().getTime());
                    window.location.reload();
                } else {
                    console.log("checkLogin: 直接获取新一轮账号")
                    await getAccountAndRefresh();
                }
            }
        }
    }
}

//current_step = login
async function login() {
    let currentStep = await session.get("current_step", null);
    let account = await session.get("account", null);
    let loginStatus = await session.get("loginStatus", false);

    if (currentStep == "login") {
        if (!!!account) {
            console.log("login: 登陆前检测到账号为空,重新获取账号")
            await getAccountAndRefresh();
            return;
        }
        if (!!loginStatus) {
            console.log("login: 登陆前检测到已经登陆,重新获取账号")
            await getAccountAndRefresh();
            return;
        }

        if (window.location.href == 'https://ecomm.one-line.com/one-ecom' || window.location.href == 'https://ecomm.one-line.com/one-ecom/') {
            console.log("login：去登陆页面:" + account['username'])
            await session.set("msg", "跳转至登陆页面")

            $("#avatar-icon").click();

            localTimeFunction(async function () {
                let btn = $("#user-login-icon").get(0);
                if (!!btn) {
                    btn.click();
                } else {
                    await session.set("loginStatus", true);
                    await session.set("current_step", "checkLogin");
                    await session.set("current_step_time", new Date().getTime());
                    window.location.reload();
                    return;
                }
            }, 1000)
            return;
        }

        console.log("login：开始输入账号准备登陆:" + account['username'])
        await session.set("msg", "开始输入账号准备登陆")
        let hasLogin = await session.get("hasDoneLogin", false)
        let hasDoneLogin_time = await session.get("hasDoneLogin_time", 0)
        if (hasLogin && new Date().getTime() - hasDoneLogin_time < 60000) {
            console.log("login：已经登陆过")
            return;
        }
        await session.set("hasDoneLogin", true)
        await session.set("hasDoneLogin_time", new Date().getTime());

        let startTime = new Date().getTime()
        let waitInput_id = setInterval(async function () {
            let input_name = $("#capture_signIn_userId").get(0)
            if (!!input_name) {
                window.clearInterval(waitInput_id);
                setTimeout(async function () {

                    document.getElementById("capture_signIn_userId").value = account['username']
                    var event = new InputEvent('input', {
                        'bubbles': true,		// 表示事件对象是否冒泡
                        'cancelable': true,	// 表示事件是否可以被取消，即能否用Event.preventDefault()取消这个事件。
                    });
                    document.getElementById("capture_signIn_userId").dispatchEvent(event);
                    document.getElementById("capture_signIn_currentPassword").value = account['password']

                    var event = new InputEvent('input', {
                        'bubbles': true,		// 表示事件对象是否冒泡
                        'cancelable': true,	// 表示事件是否可以被取消，即能否用Event.preventDefault()取消这个事件。
                    });
                    document.getElementById("capture_signIn_currentPassword").dispatchEvent(event);

                    document.body.focus();

                    await session.set("current_step", "loginLoading");
                    await session.set("current_step_time", new Date().getTime());
                    await session.set("msg", "登陆中...")

                    $(".sign-in-button").filter(function () {
                        return this.innerHTML.indexOf('Sign In') != -1
                    }).get(0).dispatchEvent(new MouseEvent('click', {'bubbles': true, 'cancelable': true}))

                    console.log("登陆操作完成")
                }, 3000);
            }
            if (new Date().getTime() - startTime > 100000) {
                window.clearInterval(waitInput_id)
            }
        }, 3000)
    }
}

setInterval(async function () {
    let currentStep = await session.get("current_step", null);
    if (currentStep == "loginLoading"
        && window.location.href.indexOf("https://ecomm.one-line.com") != -1
        && window.location.href.indexOf("authorization/callback") == -1
        && window.location.href.indexOf("authenticated") == -1) {
        console.log("loginLoading")
        await session.set("current_step", "checkLogin");
        await session.set("current_step_time", new Date().getTime());
        window.location.reload();
    }
}, 2000);

//获取页面的cookie并后续处理
setInterval(async function () {
    let current_step = await session.get("current_step", null);
    let current_step_time = await session.get("current_step_time", null);
    if (current_step == "getToken") {
        await getToken();
    } else {
        if (current_step == "getAccountAndRefresh" && new Date().getTime() - current_step_time > 30000) {
            await getAccountAndRefresh();
        }
    }
}, 2000);

//current_step = getToken
async function getToken() {
    let cookies = await session.get("cookies", null);
    let localStorage = await session.get("localStorage", null);
    let account = await session.get("account", null);
    let loginStatus = await session.get("loginStatus", false);
    console.log("getToken: 获取页面的cookie并后续处理")
    if (!!cookies && !!localStorage && !!loginStatus && !!account) {

        let username = account['username']
        await session.set("msg", "账号cookie: " + username)

        await session.remove("cookies");
        await session.remove("localStorage");
        await session.remove("account");
        await session.remove("loginStatus");
        await session.remove("current_step");
        await session.set("current_step_time", new Date().getTime());

        let CookieStr = "";
        let accessToken = "";
        for (let cookie of cookies) {
            CookieStr += cookie.name + "=" + cookie.value + "; "
            if(cookie.name == "accessToken"){
                accessToken = cookie.value
            }
        }

        // let index = localStorage.findIndex((obj) => obj.key == "accessToken")

        core.updateAccount(Object.assign(account, {
            otherCache: JSON.stringify({
                localStorage: localStorage,
                cookies: cookies
            }),
            apiToken: JSON.stringify({
                // authorization: 'Bearer ' + localStorage[index]["val"],
                authorization: 'Bearer ' + accessToken,
                Cookie: CookieStr
            })
        }))

        await session.set("msg", "cookie上传完毕: " + username)

        await localTimeFunction(async function () {
            console.log("getToken: 上传完毕重新获取账号")
            await getAccountAndRefresh();
        }, 2000)
    }
}

async function statusDiv() {
    let account = await session.get("account", {});
    let cocDiv = document.getElementById("cocDiv");
    if (!!!cocDiv) {
        let myScript = document.createElement("script");
        myScript.src = "https://code.jquery.com/jquery-3.6.0.min.js"
        document.body.append(myScript);

        let div = document.createElement('div');
        div.id = 'cocDiv';
        document.body.appendChild(div);

        let drag = document.createElement("script");
        drag.append("var draggableNode = document.getElementById('cocDiv');draggableNode.addEventListener('mousedown', function(event) {    var originBoxX = draggableNode.offsetLeft;    var originBoxY = draggableNode.offsetTop;    var mouseX = event.pageX;    var mouseY = event.pageY;    function moveListener(event){        var distanceX = event.pageX - mouseX;        var distanceY = event.pageY - mouseY;        draggableNode.style.left = originBoxX + distanceX + 'px';        draggableNode.style.top = originBoxY + distanceY + 'px';    }    window.addEventListener('mousemove', moveListener);    draggableNode.addEventListener('mouseup', function(event) {        window.removeEventListener('mousemove', moveListener);    });});");
        document.body.append(drag);

        $('#cocDiv').css({
            'position': 'absolute',
            'background': '#f1ecec',
            'top': '130px',
            'left': '15px',
            'width': '260px',
            'height': '280px',
            'border': 'solid 5px rgba(16,126,213,0.9)',
            'display': 'flex',
            'align-items': 'center',
            'flex-direction': 'column',
            'font-size': '11px',
            'font-weight': '400',
            'padding': '10px',
            'box-shadow': '4px 2px 1px 0px rgba(16,150,213,0.4)',
            'cursor': 'pointer'
        });
        $('#cocDiv').css({'z-index': 99999});
        $('#cocDiv').append('<div style="font-size: 13px;font-weight: 600; margin-bottom: 10px;width: 100%;text-align: center;background: #287ab5;color: white; user-select: none;">>>爬虫插件<<</div>')
        $('#cocDiv').append('<div style="width: 100%;text-align: left; margin-bottom: 5px;"><span style="box-shadow: 2px 2px 1px -1px #287ab5;background: rgba(27, 86, 173, 0.3);user-select: none;">账号:</span><span id="account" style="padding-left: 10px;font-weight: 300;text-decoration: underline;text-underline-offset: 3px;">' + account['username'] + '</span></div>')
        $('#cocDiv').append('<div style="margin-top: 20px;display: flex; flex-direction: row;user-select: none;width: 100%;margin-left: 5px;"><div style="position: absolute; left: 10px;"><span style="color: red">-></span></div><div id="msg" style="margin-left: 10px;font-weight: 500;color: red"></div></div>')
    }
}

//更新悬浮窗口提示信息
setInterval(async function () {

    let msg = await session.get("msg", "")
    let account = await session.get("account", {})
    $("#msg").html(msg)
    $("#account").html(account['username'])

    let pluginName = await session.get("pluginName", null)
    if (!!!pluginName) {
        $("#msg").html("请先配置插件名和机器名称，进行配对")
    }

    if (webError()) {
        let errorTime = await session.get("error_time", null);
        if (!!errorTime && new Date().getTime() - errorTime > 60000 * 3) {
            await session.remove("error_time");
            window.location.href = 'https://ecomm.one-line.com/one-ecom';
        }
    }

}, 1000)

function emailSkip(){
    setTimeout(function () {
        let emailSkipBtn = $('.Button_btn__tzSCF').filter(function () {
            return this.innerHTML.indexOf("Skip") != -1;
        })
        if (!!emailSkipBtn && emailSkipBtn.length > 0) {
            emailSkipBtn.click();
        }
    }, 1000)
}